package com.service;

import com.entity.VehicleInfo;
import com.repository.VehicleInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
@Transactional
public class VehicleInfoService {

    @Autowired
    private VehicleInfoRepository vehicleInfoRepository;

    /**
     * 保存车辆信息
     * @param vehicleInfo 车辆信息
     * @return 保存后的对象
     */
    public VehicleInfo save(VehicleInfo vehicleInfo) {
        if (vehicleInfo.getId() == null) {
            vehicleInfo.setCreateTime(new Date());
        }
        vehicleInfo.setUpdateTime(new Date());
        return vehicleInfoRepository.save(vehicleInfo);
    }

    /**
     * 根据ID删除车辆信息
     * @param id ID
     */
    public void deleteById(Integer id) {
        vehicleInfoRepository.deleteById(id);
    }

    /**
     * 根据ID获取车辆信息
     * @param id ID
     * @return 车辆信息
     */
    @Transactional(readOnly = true)
    public Optional<VehicleInfo> findById(Integer id) {
        return vehicleInfoRepository.findById(id);
    }

    /**
     * 分页查询车辆信息
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<VehicleInfo> findAll(int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        return vehicleInfoRepository.findAll(pageable);
    }

    /**
     * 根据车牌号模糊查询车辆信息
     * @param plateNumber 车牌号
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<VehicleInfo> findByPlateNumberContaining(String plateNumber, int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        return vehicleInfoRepository.findByPlateNumberContaining(plateNumber, pageable);
    }
}